package cn.hejiang.mamis.access.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.ssssssss.magicapi.core.web.RequestHandler;

import cn.hejiang.mamis.core.constant.ResultCode;
import cn.hejiang.mamis.core.dto.ResultDTO;
import cn.hejiang.mamis.core.entity.PlatSys;
import cn.hejiang.mamis.core.entity.SessionDetails;
import cn.hejiang.mamis.core.service.ContextService;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class AccessInterceptor implements HandlerInterceptor {
	@Autowired
	ContextService contextService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		final SessionDetails details = contextService.getSessionFromRequest(request);

		if (details == null) {
			final String ctxPath = request.getContextPath();
			final String uri = request.getRequestURI();

			if (isAjax(request)) {
				response.setContentType("application/json");
				response.getWriter().println(JSONUtil.toJsonStr(new ResultDTO(ResultCode.NotLogin, "登录失效", null)));
				log.error("未登录访问: {} 返回无权限信息", request.getRequestURI());
			} else {
				response.sendRedirect(ctxPath + "/mamis/access/login?redirect=" + uri);
				log.error("未登录访问: {} 跳转登录页面", request.getRequestURI());
			}
			return false;
		}

		
		// 检查请求头
		PlatSys sys = contextService.getSystemFromRequest(request);

		if (handler != null && handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Class<?> clazz = handlerMethod.getBean().getClass();
			// 提取处理类，判断是否是`magic-api`的处理器
			if (clazz == RequestHandler.class) {
				log.info("放行 magic-api 调用: {}", request.getRequestURI());
				return true;
			}

			// 判断是否核心接口
			if (clazz.getPackage().getName().equals("cn.hejiang.mamis.core.controller")) {
				if (sys == null) {
					response.setContentType("application/json");
					response.getWriter().println(JSONUtil.toJsonStr(new ResultDTO(ResultCode.NotLogin, "未指定目标系统", null)));
					log.error("阻止无系统访问: {}", request.getRequestURI());
					return false;
				}
			}
		}

		log.debug("放行: {}", request.getRequestURI());
		return true;
	}

	protected boolean isAjax(HttpServletRequest request) {
		String dest = request.getHeader("Sec-Fetch-Dest");
		if ("iframe".equals(dest) || "document".equals(dest)) {
			return false;
		}

		// String header = request.getHeader("X-Requested-With");
		// String contentType = request.getContentType();
		// if(header != null && header.equals("XMLHttpRequest") ||
		// "application/json".equals(contentType)){
		// return true;
		// }

		return true;
	}

}
